<?php

namespace App\Manage;


use App\Models\Goods;
use App\Models\GoodsCate;
use App\Models\GoodsDesc;
use App\Models\User;

class GoodsManage extends Manage
{

    // TODO 操作日志

    protected function getModel()
    {
        return new Goods();
    }

    // 列表
    public function lists($myUser, $options = [])
    {

        // 参数
        $is_admin_log = $options['is_admin_log'] ?? 0;


        $opt     = $this->option();
        $page    = $opt->getData('page', 1, 'intval');
        $rows    = $opt->getData('rows', 15, 'intval');
        $keyword = $opt->getData('keyword', null, 'trim');
        $cate_id = $opt->getData('cate_id', null, 'intval');
        $uid     = $opt->getData('uid', null, 'intval');
        $isLine  = $opt->getData('is_online', 1, 'intval');
        $verify  = $opt->getData('status', null, 'intval');

        // 条件
        $where = $cache = [];  //  ['is_online', '=', $isLine]
        if(is_null($verify)){
            $where[] = ['status', '>=', 0];
        } else{
            $where[] = ['status', '=', $verify];
            // 缓存
            $cache['status'] = $verify;
        }
        if($uid){
            $where[] = ['uid', '=', $uid];
            // 缓存
            $cache['uid'] = $uid;
        }
        if($cate_id){
            $where[] = ['cate_id', '=', $cate_id];
            // 缓存
            $cache['cate_id'] = $cate_id;
        }
        if($keyword){
            $where[] = $opt->orWhere('title|content', 'like', $keyword);
            // 缓存
            $cache = false;
        }

        // 模型 和 查询
        $model = new Goods();
        if(empty($cache)){
            $result = $model->listPage($where, $page, $rows, "id DESC");
        } else{
            $result = $model->listPageCache($cache, $where, $page, $rows, "id DESC");
        }

        // 数据整理
        if($result['list']){
            $cateDb = new GoodsCate();
            $cids   = array_column($result['list'], 'cate_id');
            $cates  = $cateDb->getListInIdsCache($cids);
            foreach($result['list'] as $key => $item){
                $_cid  = $item['cate_id'];
                $_cate = $cates[$_cid] ?? [];

                // 整理
                //$result['list'][$key]['cover']     = $this->getFullUrl($item['cover']);
                $result['list'][$key]['cate'] = $_cate;
            }
        }

        return $result;
    }

    // 删除（软删除）
    // 软删除
    public function softDel($field = 'status', $myUser = [], $options = [])
    {

        // 参数
        $is_admin_log = $options['is_admin_log'] ?? 0;


        $opt = $this->option();
        $id  = $opt->getData('id', 0, 'intval');
        $ids = $opt->getData('ids', [], 'is_array');
        // 修改记录
        if(empty($id) && empty($ids)){
            //return $this->_returnFail('请指定删除记录！');
            return $this->_returnFail('select_operation_id');
        }

        // 模型
        /** @var  $model \App\Models\Base */
        $model = $this->getModel();
        if($model === false){
            return $this->_returnFail('specify_the_operational_model');
            //return $this->_returnFail('请指定操作模型');
        }

        // 条件
        $where = [];
        if($id){
            $where[] = ['id', '=', $id];
        }
        if($ids){
            $where[] = [
                function($qq) use ($ids) {
                    $qq = $qq->whereIn('id', $ids);
                },
            ];
        }

        // 查询
        $lists = $model->where($where)->get()->toArray();;  //->recycle()
        if(empty($lists)){
            //return $this->_returnFail('你要删除的数据不存在！！');
            return $this->_returnFail('data_delete_has_not_exist');
        }

        // 缓存操作
        $model->deleteCacheList($lists);

        // 删除
        $res = $model->where($where)->update([$field => -1]);

        // 管理员日志
        if($is_admin_log){
            //$this->addAdminLog($myUser['id'], '删除商品');
        }

        return true;
    }

    // 详情
    public function show($myUser, $options = [])
    {


        // 参数
        $is_admin_log = $options['is_admin_log'] ?? 0;


        $opt     = $this->option();
        $id      = $opt->getData('id', 0, 'intval');
        $isBuild = $opt->getHeader('Build-Admin', 0, 'intval');
        if(empty($id)){
            //return $this->_returnFail('请指定查看记录！');
            return $this->_returnFail('select_operation_id');
        }


        $where = [['id', '=', $id],]; // ['status', '=', 1]
        $model = new Goods();
        $info  = $model->oneFindCache(['id' => $id], $where);
        if($info === false){
            return $this->_returnFail($model->getError());
        }
        if(empty($info)){
            //return $this->_returnFail('你要查看的商品不存在！');
            return $this->_returnFail('data_has_not_exist');
        }

        // 整理详情
        $info   = is_object($info) ? $info->toArray() : $info;
        $descDb = new GoodsDesc();
        $desc   = $descDb->getOneByIdCache($info['id'], '*', 'goods_id');
        if($desc){
            $info = array_merge($desc, $info);
        }


        // 数据整理
        //$info['cover']  = $this->getFullUrl($info['cover']);
        //$info['images'] = $info['images'] ? json_decode($info['images'], true) : [];
        // 查找用户信息
        if($info['cate_id']){
            $cid    = $info['cate_id'];
            $cateDb = new GoodsCate();
            $cate   = $cateDb->getOneByIdCache($cid);
            // 整理
            $info['cate'] = $cate;
        }

        // 如果是build-admin
        if($isBuild){
            return ['row' => $info];
        }

        return $info;
    }

    // 启用禁用
    public function status($myUser, $options = [])
    {


        // 参数
        $is_admin_log = $options['is_admin_log'] ?? 0;


        $opt    = $this->option();
        $id     = $opt->getData('id', 0, 'intval');
        $status = $opt->getData('status', 0, 'intval');
        if(empty($id)){
            //return $this->_returnFail('请指定查看记录！');
            return $this->_returnFail('select_operation_id');
        }
        if(is_null($status)){
            //return $this->_returnFail('是否启用状态必须填写！！');
            return $this->_returnFail('enable_disable_status_must_be_filled');
        }
        if(!in_array($status, [0, 1, -1])){
            //return $this->_returnFail('是否启用状态必须为0或1！！');
            return $this->_returnFail('status_value_must_be_0_1');
        }


        // 执行
        $model  = new Goods();
        $result = $model->oneEdit(['id' => $id], ['status' => $status]);
        if($result === false){
            return $this->_returnFail($model->getError());
        }
        // 管理员日志
        /*if($is_admin_log){
            $this->addAdminLog($myUser['id'], '修改自己的个人资料', '');
        }*/

        return true;
    }


    // 改变（直接修改，软删除，改变状态，排序）
    public function edit($myUser, $options = [])
    {
        $opt     = $this->option();
        $id      = $opt->getData('id', 0, 'intval');
        $images  = $opt->getData('images', [], 'is_array');
        $content = $opt->getData('content', '', 'trim');
        $pic     = $opt->getData("pic", '', 'trim');
        if(empty($id)){
            //return $this->_returnFail('请指定查看记录！');
            return $this->_returnFail('select_operation_id');
        }
        if(count($images) != count($images, 1)){
            //return $this->_returnFail('请传递正确图片地址！');
            return $this->_returnFail('provide_correct_image_url');
        }


        // 参数
        $is_admin_log = $options['is_admin_log'] ?? 0;


        // 数据
        $data = [
            'status'        => $opt->getData("status", 1, 'intval'),
            'is_start'      => $opt->getData("is_start", null, 'intval'),
            'is_short_sale' => $opt->getData("is_short_sale", null, 'intval'),
            'cate_id'       => $opt->getData("cate_id", 1, 'intval'),
            'stock'         => $opt->getData("stock", 0, 'intval'),
            'rank'          => $opt->getData('rank', 0, 'intval'),
            'name'          => $opt->getData("name", '', 'trim'),
            'pic'           => $pic,
            'price'         => $opt->getData("price", 0, 'floatval'),
            'market_price'  => $opt->getData("market_price", 0, 'floatval'),
            'images'        => json_encode($images),
            'content'       => $content,
            // 商品的属性与值
            'attr_1_name'   => $opt->getData("attr_1_name", '', 'trim'),
            'attr_2_name'   => $opt->getData("attr_2_name", '', 'trim'),
            'attr_1_1'      => $opt->getData("attr_1_1", '', 'trim'),
            'attr_1_2'      => $opt->getData("attr_1_2", '', 'trim'),
            'attr_1_3'      => $opt->getData("attr_1_3", '', 'trim'),
            'attr_2_1'      => $opt->getData("attr_2_1", '', 'trim'),
            'attr_2_2'      => $opt->getData("attr_2_2", '', 'trim'),
            'attr_2_3'      => $opt->getData("attr_2_3", '', 'trim'),
        ];


        // 组合数据
        $model = new Goods();
        // 这里是多表操作 不能这样过滤
        /*$data  = $model->filterField($data, true);
        if($data === false){
            return $this->_returnFail($model->getError());
        }
        if(empty($data)){
            //return $this->_returnFail('不能修改为空！');
            return $this->_returnFail('send_data_to_be_modify');
        }*/
        // 设置 content
        if($data['content']){
            $data['content'] = $model->setContentAttribute($data['content']);
        }
        if($data['images']){
            $data['images'] = $model->setImagesAttribute($data['images']);
        }
        // 设置pic
        if($data['pic']){
            $data['pic'] = $model->setPicAttribute($data['pic']);
        }

        // TODO 审核
        //$this->baiduTextCensor($data);


        // 执行
        $where  = ['id' => $id];
        $result = $model->oneEdit($where, $data);
        if($result === false){
            return $this->_returnFail($model->getError());
        }


        return true;
    }


    // 添加
    public function add($myUser, $options = [])
    {
        // 数据
        $opt     = $this->option();
        $images  = $opt->getData('images', [], 'is_array');
        $content = $opt->getData('content', '', 'trim');
        $pic     = $opt->getData("pic", '', 'trim');
        $ip      = $opt->request()->ip();
        $ip      = '';
        if(empty($content)){
            //return $this->_returnFail('请填写内容!');
            return $this->_returnFail('fill_the_content');
        }

        // TODO 提取图片
        if(count($images) != count($images, 1)){
            //return $this->_returnFail('请传递正确图片地址！');
            return $this->_returnFail('provide_correct_image_url');
        }
        if(empty($pic) && $images){
            $pic = $images[0];
        }

        // 参数
        $is_admin_log = $options['is_admin_log'] ?? 0;


        // TODO 审核
        //$this->baiduTextCensor($data);

        $data = [
            'status'        => $opt->getData("status", 1, 'intval'),
            'is_start'      => $opt->getData("is_start", 0, 'intval'),
            'is_short_sale' => $opt->getData("is_short_sale", 0, 'intval'),
            'cate_id'       => $opt->getData("cate_id", 1, 'intval'),
            'stock'         => $opt->getData("stock", 0, 'intval'),
            'rank'          => $opt->getData('rank', 0, 'intval'),
            'name'          => $opt->getData("name", '', 'trim'),
            'pic'           => $pic,
            'price'         => $opt->getData("price", 0, 'floatval'),
            'market_price'  => $opt->getData("market_price", 0, 'floatval'),
            'images'        => json_encode($images),
            'content'       => $content,
            'ip'            => $ip,
            // 商品的属性与值
            'attr_1_name'   => $opt->getData("attr_1_name", '', 'trim'),
            'attr_2_name'   => $opt->getData("attr_2_name", '', 'trim'),
            'attr_1_1'      => $opt->getData("attr_1_1", '', 'trim'),
            'attr_1_2'      => $opt->getData("attr_1_2", '', 'trim'),
            'attr_1_3'      => $opt->getData("attr_1_3", '', 'trim'),
            'attr_2_1'      => $opt->getData("attr_2_1", '', 'trim'),
            'attr_2_2'      => $opt->getData("attr_2_2", '', 'trim'),
            'attr_2_3'      => $opt->getData("attr_2_3", '', 'trim'),
        ];

        // 组合数据
        $model = new Goods();
        // 这里是多表操作 不能这样过滤
        /*$data  = $model->filterField($data, true);
        if($data === false){
            return $this->_returnFail($model->getError());
        }*/
        if(empty($data)){
            //return $this->_returnFail('请填写添加的数据！');
            return $this->_returnFail('add_the_saved_data');
        }
        // 设置 content
        if($data['content']){
            $data['content'] = $model->setContentAttribute($data['content']);
        }
        if($data['images']){
            $data['images'] = $model->setImagesAttribute($data['images']);
        }
        // 设置pic
        if($data['pic']){
            $data['pic'] = $model->setPicAttribute($data['pic']);
        }

        // 验证
        $rules  = ['name' => 'required', 'content' => 'required',];
        $result = $opt->validator($data, $rules);
        if($result === false){
            return $this->_returnFail($opt->getError());
        }

        // 保存
        $result = $model->oneAdd($data);

        if($result === false){
            return $this->_returnFail($model->getError());
        }


        // 管理员日志
        if($is_admin_log){
            //$this->addAdminLog($myUser['id'], '添加商品');
        }


        return true;
    }


}

